import { calculateCentroid3D } from '@/utils/common'
import { v4 as uuid } from 'uuid'
import { useAirCityStore } from '@/stores/aircity'

import { useBuilding } from '@/hooks/usebuildingTilelayers'
import { ref } from 'vue'
import { floorInfo } from './points'
import { INFO } from './info'
import { requireImg } from '@/utils/common'
// 1打印机，2自动售票机，3安检机器，4智能监控，5灭火器，6自动扶梯，7车站大屏幕，8温湿度传感器，9导流牌
import deviceJson from '../../../mock/device.json'
import { cloneDeep } from 'lodash'

const airStore = useAirCityStore()
export const drawPolygon3d = (area: any, height: number = 40) => {
	let list = cloneDeep(area.list)
	if (!Array.isArray(list)) {
		list = [list]
	}

	let pls = list.map((item: any) => {
		item.coordinates.forEach((_: number[]) => {
			_[2] -= 7.5
		})
		let pl = {
			id: (area.type || 'area-fence') + uuid(),
			groupId: area.type || 'area-fence',
			coordinates: item.coordinates,
			coordinateType: 0, //坐标系类型，取值范围：0为Projection类型，1为WGS84类型，2为火星坐标系(GCJ02)，3为百度坐标系(BD09)，默认值：0
			height, //3D多边形的高度
			intensity: 0.05, //亮度
			color: [39 / 255, 101 / 255, 164 / 255, 0.8],
			style: 5, //3DPolygon的样式 请参照API开发文档选取枚举
			tillingX: 0, //可选，仅当3DPolygon的样式支持贴图显示，贴图横向平铺
			tillingY: 0, //可选，仅当3DPolygon的样式支持贴图显示，贴图纵向平铺

			generateTop: false, //是否生成顶面
			generateSide: true, //是否生成侧面
			generateBottom: false, //是否生成底面
		}
		return pl
	})
	fdapi.polygon3d.add(pls)
	// drawText(area)

	addAreaMarker3d(
		list.map((item: any, i: number) => {
			// item.coordinates[2] -= 6.5
			let c = calculateCentroid3D(item.coordinates)
			return {
				name: '安检区域-标签' + i,
				coordinate: [c[0], c[1], c[2] + 24],
				lineColor: [12946195.0, 4844110.0, 88.7],
				color: [0, 0.25, 1, 1],
			}
		}),
	)
}

export const drawText = (area: any) => {
	let list = area?.list
	if (!Array.isArray(list)) {
		list = [list]
	}
	let marker3d = list.map((item: any, i: any) => {
		const coordinate = calculateCentroid3D(item.coordinates)
		let o = {
			id: area.type + uuid(),
			groupId: area.type,
			text: area.type, //3D标注显示文字
			textSize: 100, //3D标注显示文字大小
			textColor: Color.Red, //3D标注显示文字颜色
			textOutlineSize: 0, //3D标注显示文字轮廓大小
			textOutlineColor: Color.White, // 3D标注显示文字轮廓颜色
			textFixed: false, // 3D标注显示文字是否固定文本朝向
			fixedSize: true, // 默认尺寸 非近大远小
			textVisible: true, //3D标注显示文字是否显示文本
			textLocation: [0, 0, 0], // 文字位置
			textRotation: [0, 0, 0], // 文字旋转
			textScale: [100, 100, 100], // 文字缩放
			pointName: 'Point_B_5', //3D标注展示的特效名称
			pointVisible: false, //3D标注是否显示
			pointScale: 2, //3D标注整体缩放比例
			coordinate: [coordinate[0], coordinate[1], coordinate[2] + 43], //3D标注的坐标位置 注意：若坐标Z设置高度为0时 autoHeight=true则会显示在物体上方
			coordinateType: 0, //坐标系类型
			range: [1, 1000000], //3D标注的可视距离范围：[min,max]，单位：米
			autoHeight: false, //自动判断下方是否有物体，设置正确高度，默认值：false
		}

		return o
	})
	__g.marker3d.add(marker3d)
}

export const addEquipmentMarker = async (equipment: any, type = 'marker') => {
	// let list = cloneDeep(equipment?.equipments)
	let list = deviceJson.data.records.filter((dItem) => {
		return dItem.type == equipment
	});
	if (!Array.isArray(list)) {
		list = [list]
	}

	console.log("listlist=====", list);


	console.log("item id=====", equipment);

	// let info: any = INFO[equipment.type]
	// let info: any = deviceJson.data.records;
	// console.log("deviceJson===", info)

	if (type == 'marker') {
		await fdapi.marker.deleteByGroupId('自动售票机器')

		let imgs = requireImg('global/自动售票机.png')

		const mks = list.map((item: any, i: any) => {
			if (item.coordinate) {
				item.coordinate = item.coordinate.split(',').map((cItem: any) => parseFloat(cItem.trim()));;
			}
			console.log("list item=====", item);
			console.log(`avator img ======${window.origin}/icon/${item.avatar}`)
			item.coordinate[2] -= 7.5
			//支持经纬度坐标和普通投影坐标两种类型
			let m = {
				id: item.id || 'area-marker' + uuid(),
				groupId: "自动售票机器",
				coordinate: item.coordinate, //坐标位置
				coordinateType: 0, //默认0是投影坐标系，也可以设置为经纬度空间坐标系值为1
				anchors: [-25, 80], //锚点，设置Marker的整体偏移，取值规则和imageSize设置的宽高有关，图片的左上角会对准标注点的坐标位置。示例设置规则：x=-imageSize.width/2，y=imageSize.height
				imageSize: [50, 80], //图片的尺寸
				// hoverImageSize: [50, 50], //鼠标悬停时显示的图片尺寸
				range: [0, 10000000], //可视范围
				viewHeightRange: [0, 1000000], // 可见高度范围
				rangeRatio: 0.01, //可见高度范围的调整系数
				imagePath: `${window.origin}/icon/${item.avatar}`, //显示图片路径
				// hoverImagePath: HostConfig.Path + '/samples/images/hilightarea.png', // 鼠标悬停时显示的图片路径
				fixedSize: true, //图片固定尺寸，取值范围：false 自适应，近大远小，true 固定尺寸，默认值：false

				text: item.text + i, //显示的文字
				useTextAnimation: false, //关闭文字展开动画效果 打开会影响效率
				textRange: [0, 1000], //文本可视范围[近裁距离, 远裁距离]
				textOffset: [0, 0], // 文本偏移
				textBackgroundColor: Color.SpringGreen, //文本背景颜色
				fontSize: 24, //字体大小
				fontOutlineSize: 1, //字体轮廓线大小
				fontColor: Color.White, //字体颜色
				fontOutlineColor: Color.Black, //字体轮廓线颜色

				popupURL: `${window.origin}/popup/equipmentInfo.html?info=${item.ext}&img=${imgs}`, //弹窗HTML链接
				popupBackgroundColor: [1.0, 1.0, 1.0, 1], //弹窗背景颜色
				popupSize: [950, 500], //弹窗大小
				popupOffset: [0, 0], //弹窗偏移
				showLine: false, //标注点下方是否显示垂直牵引线
				lineSize: [2, 10], //垂直牵引线宽度和高度[width, height]
				lineColor: Color.SpringGreen, //垂直牵引线颜色
				lineOffset: [0, 0], //垂直牵引线偏移
				autoHidePopupWindow: true, //失去焦点后是否自动关闭弹出窗口
				autoHeight: false, // 自动判断下方是否有物体
				displayMode: 4, //智能显示模式  开发过程中请根据业务需求判断使用四种显示模式
				clusterByImage: true, // 聚合时是否根据图片路径分类，即当多个marker的imagePath路径参数相同时按路径对marker分类聚合
				priority: 0, //避让优先级
				occlusionCull: false, //是否参与遮挡剔除
			}
			return m
		})

		fdapi.marker.add(mks)
	} else {
		fdapi.marker3d.deleteByGroupId(equipment.type)
		const mks = list.map((item: any, i: any) => {
			let o = {
				id: item.id || 'area-marker' + uuid(),
				groupId: item.groupId || equipment.type,
				coordinate: item.coordinate, //坐标位置
				text: 'Building No.1', //3D标注显示文字
				textSize: 32, //3D标注显示文字大小
				textColor: '#6BF4F7', //3D标注显示文字颜色
				textOutlineSize: 1, //3D标注显示文字轮廓大小
				textOutlineColor: Color.Black, // 3D标注显示文字轮廓颜色
				textFixed: true, // 3D标注显示文字是否固定文本朝向
				fixedSize: true, // 默认尺寸 非近大远小
				textVisible: false, //3D标注显示文字是否显示文本
				textLocation: [0, 0, 0], // 文字位置
				textRotation: [0, 90, 0], // 文字旋转
				textScale: [10, 10, 10], // 文字缩放
				pointName: '3D_UI_C_4', //3D标注展示的特效名称
				pointVisible: true, //3D标注是否显示
				pointScale: 2, //3D标注整体缩放比例
				coordinateType: 0, //坐标系类型
				range: [1, 10000], //3D标注的可视距离范围：[min,max]，单位：米
				autoHeight: false, //自动判断下方是否有物体，设置正确高度，默认值：false
			}
			return o
		})

		await fdapi.marker3d.add(mks)

		fdapi.marker3d.callBPFunction(
			mks
				.map((n: any, i: any) => {
					return [
						{
							id: n.id,
							functionName: '文字',
							parameters: [
								{ paramType: 5, paramValue: '设备异常' },
								{ paramType: 6, paramValue: [1, 1, 1, 1] },
								{ paramType: 6, paramValue: [1, 0, 0, 0.9] },
								{ paramType: 16, paramValue: '背景样式4' },
							],
						},
						{
							id: n.id,
							functionName: '图标',
							parameters: [
								{ paramType: 16, paramValue: '报错' },
								{ paramType: 16, paramValue: '图标背景A' },
							],
						},
						{
							id: n.id,
							functionName: '特效',
							parameters: [
								{ paramType: 16, paramValue: '光圈_16' },
								{ paramType: 16, paramValue: '标记点5' },
							],
						},
					]
				})
				.flat(),
		)
	}
}

export const showMarker = async (item: any) => {
	console.log("showMarker item======", item)
	if (item.camera) {
		__g.camera.set(item.camera, 1)
	}
	// const equipment = floorInfo.find((_) => _.name == floor.value)?.point.find((_) => _.type == item.title)
	// console.log("equipment=====",equipment)
	// const equipment = deviceJson.data.records.filter((dItem) => {
	// 	return dItem.type == item.id
	// })
	// console.log("equipment=====",equipment)
	addEquipmentMarker(item.id)
}

let areaMarker3ds = [
	{
		name: '地铁区域-标签',
		coordinate: [12946195.0, 4844110.0, 88.7],
		lineColor: [12946195.0, 4844110.0, 88.7],
		color: [0, 0.25, 1, 1],
	},
	{
		name: '停车场通道-标签',
		coordinate: [12945988.0, 4843966.0, 88.7],
		lineColor: [1, 0.46, 0.46, 1],
		color: [0.752, 0.169, 0.169, 1],
	},
	{
		name: '地铁出站-标签',
		coordinate: [12946123.0, 4844100.0, 88.7],
		lineColor: [1, 0.554, 0.19, 1],

		color: [0.669, 0.296, 0.167, 1],
	},
	{
		name: '枢纽出站-标签',
		coordinate: [12946215.0, 4844064.0, 88.7],
		lineColor: [0.2, 0.509, 0, 1],
		color: [0.163, 0.422, 0.08, 1],
	},
	{
		name: '地铁进站-标签',
		coordinate: [12946133.0, 4844078.5, 88.7],
		lineColor: [0.5, 0.105, 1, 1],
		color: [0.154, 0.25, 0.573, 1],
	},
	{
		name: '铁路出站通道-标签',
		coordinate: [12946099.0, 4844082.5, 88.7],
		lineColor: [1, 0.28, 0.989, 1],
		color: [0.616, 0.21, 0.637, 1],
	},
]
let yongjiMarker3ds = [
	{
		title: '铁路安检层',
		children: [
			{
				name: '枢纽闸机售票处',
				coordinate: [12946101.76, 4844036.8, 120.25000976562501],
				info: { 拥堵等级: '三级预警', 客流密度: '1500人', 拥堵时间: '2024年11月15日12:47:10', 管理班组: '火车站续接' },
			},
		],
	},
	{
		title: '多运输衔接层',
		children: [
			{
				name: '接驳枢纽',
				coordinate: [12946197.76, 4844055.04, 78.599990234375],
				info: { 拥堵等级: '三级预警', 客流密度: '865人', 拥堵时间: '2024年11月15日12:47:10', 管理班组: '停车场续接' },
			},
			{
				name: '停车场通道',
				coordinate: [12945968.64, 4843958.72, 78.5999951171875],
				info: { 拥堵等级: '一级预警', 客流密度: '500人', 拥堵时间: '2024年11月15日12:47:10', 管理班组: '停车场续接' },
			},
		],
	},
]
export const showAreas = async (item: any) => {
	console.log('floor.value', floor.value)

	if (floor.value == '铁路安检层') {
		if (!item.isActive) {
			fdapi.marker3d.deleteByGroupId('area-marker3d')
			return
		}
		const area = floorInfo.find((_) => _.name == floor.value)?.area.find((_) => _.type == item.title)
		drawPolygon3d(area)
	} else {
		//代码添加marker3d（工程加的有问题），工程添加polygon3d
		if (item.isActive) {
			await fdapi.infoTree.show(airStore.GetTreeIdByName([item.title]))
			addAreaMarker3d(areaMarker3ds.filter((_) => _.name == item.title + '-标签'))
			fdapi.marker3d.focus(item.title + '-标签', 50, 1, [-60, -120, 0])
		} else {
			await fdapi.infoTree.hide(airStore.GetTreeIdByName([item.title]))
			fdapi.marker3d.delete(item.title + '-标签')
		}
	}
}
export const drawArea = async (list: any) => {
	await removeByGroupIds(['area-marker', 'area-fence'])
	if (!Array.isArray(list)) {
		list = [list]
	}
	list.forEach((item: any) => {
		item.coordinate = calculateCentroid3D(item.coordinates)
	})

	drawPolygon3d(list)
	// addMarker(list)
}
export const addYongJiMarker3ds = async (item: any) => {
	console.log('floor.value', floor.value)
	console.log('item', item)

	let list = yongjiMarker3ds.find((_) => _.title == floor.value)?.children
	await fdapi.marker3d.deleteByGroupId('marker3d-yongji')
	await fdapi.marker.deleteByGroupId('kll')

	if (!item.isActive) {
		return
	}

	list?.forEach((_: any, i: any) => add3dMarker(_.coordinate, i, _.name, _.info))
}
const add3dMarker = async (coordinate: any, i: any, title: any, info: any) => {
	//   await fdapi.marker3d.delete('m1')
	coordinate[2] -= 6
	let o = {
		id: 'm1' + i,
		groupId: 'marker3d-yongji',
		text: 'Building No.1', //3D标注显示文字
		textSize: 32, //3D标注显示文字大小
		textColor: '#6BF4F7', //3D标注显示文字颜色
		textOutlineSize: 1, //3D标注显示文字轮廓大小
		textOutlineColor: Color.Black, // 3D标注显示文字轮廓颜色
		textFixed: true, // 3D标注显示文字是否固定文本朝向
		fixedSize: true, // 默认尺寸 非近大远小
		textVisible: false, //3D标注显示文字是否显示文本
		textLocation: [0, 0, 0], // 文字位置
		textRotation: [0, 90, 0], // 文字旋转
		textScale: [10, 10, 10], // 文字缩放
		pointName: '3D_UI_C_4', //3D标注展示的特效名称
		pointVisible: true, //3D标注是否显示
		pointScale: 2, //3D标注整体缩放比例
		coordinate: coordinate, //3D标注的坐标位置 注意：若坐标Z设置高度为0时 autoHeight=true则会显示在物体上方
		coordinateType: 0, //坐标系类型
		range: [1, 10000], //3D标注的可视距离范围：[min,max]，单位：米
		autoHeight: false, //自动判断下方是否有物体，设置正确高度，默认值：false
		userData: JSON.stringify({
			...info,
		}),
	}
	await fdapi.marker3d.add(o)
	__g.marker3d.focus('m1', 50, 0)

	fdapi.marker3d.callBPFunction([
		{
			id: 'm1' + i,
			functionName: '文字',
			parameters: [
				{ paramType: 5, paramValue: title },
				{ paramType: 6, paramValue: [1, 1, 1, 1] },
				{ paramType: 6, paramValue: info['拥堵等级'] == '三级预警' ? [1, 0, 0, 0.9] : [1, 1, 0, 0.9] },
				{ paramType: 16, paramValue: '背景样式4' },
			],
		},
		{
			id: 'm1' + i,
			functionName: '图标',
			parameters: [
				{ paramType: 16, paramValue: '众多用户' },
				{ paramType: 16, paramValue: '图标背景A' },
			],
		},
		{
			id: 'm1' + i,
			functionName: '特效',
			parameters: [
				{ paramType: 16, paramValue: '光圈_16' },
				{ paramType: 16, paramValue: '标记点5' },
			],
		},
	])
}
const removeByGroupIds = async (groupIds: string[]) => {
	let p = groupIds.map((groupId) => fdapi.infoTree.deleteByGroupId(groupId))
	await Promise.all(p)
}

export const addAreaMarker3d = async (lists: any) => {
	let list = cloneDeep(lists)
	const mks = list.map((item: any, i: any) => {
		item.coordinate[2] -= 10
		let o = {
			id: item.animId || item.name,
			groupId: item.groupId || 'area-marker3d',
			userData: JSON.stringify(item),
			coordinate: item.coordinate, //坐标位置
			text: 'Building No.1', //3D标注显示文字
			textSize: 32, //3D标注显示文字大小
			textColor: '#ffffff', //3D标注显示文字颜色
			textOutlineSize: 1, //3D标注显示文字轮廓大小
			textOutlineColor: Color.Black, // 3D标注显示文字轮廓颜色
			textFixed: true, // 3D标注显示文字是否固定文本朝向
			fixedSize: false, // 默认尺寸 非近大远小
			textVisible: false, //3D标注显示文字是否显示文本
			textLocation: [0, 0, 0], // 文字位置
			textRotation: [0, 90, 0], // 文字旋转
			textScale: [10, 10, 10], // 文字缩放
			pointName: '3D_UI_B_1', //3D标注展示的特效名称
			pointVisible: true, //3D标注是否显示
			pointScale: 5, //3D标注整体缩放比例
			coordinateType: 0, //坐标系类型
			range: [0, 10000], //3D标注的可视距离范围：[min,max]，单位：米
			autoHeight: false, //自动判断下方是否有物体，设置正确高度，默认值：false
		}
		return o
	})
	const cloneMks = cloneDeep(mks)
	await fdapi.marker3d.add(mks)

	fdapi.marker3d.callBPFunction(
		cloneMks
			.map((n: any, i: any) => {
				console.log('n.userData', n.userData)

				const data = JSON.parse(n.userData)
				return [
					{
						id: n.id,
						functionName: '文字',
						parameters: [
							{ paramType: 5, paramValue: data.name.split('-')[0] },
							{ paramType: 2, paramValue: 48 },
							{ paramType: 6, paramValue: [1, 1, 1, 1] },
						],
					},
					{
						id: n.id,
						functionName: '背景',
						parameters: [
							{ paramType: 3, paramValue: 1 },
							{ paramType: 3, paramValue: 0.5 },
							{ paramType: 3, paramValue: 10 },
							{ paramType: 6, paramValue: data.color },
							{ paramType: 6, paramValue: data.lineColor },
							{ paramType: 16, paramValue: '纵向渐变' },
						],
					},
				]
			})
			.flat(),
	)
}
/**
 * x光
 */

export const changeXRay = async (flag: boolean = true) => {
	const treeIdByName = airStore.GetTreeIdByName([''])
	// await __g.weather.setDateTime(2024, 3, 15, 7, 0, false)

	if (flag) {
		await __g.tileLayer.enableXRay([...treeIdByName], [0, 0, 1, 0.1])
	} else {
		await __g.tileLayer.disableXRay([...treeIdByName])
	}
}

// export const buildingLayering = () => {
// 	changeXRay(true)

// 	export let building: any = useBuilding(buildingStore.buildingOption as any)

// 	export const buildingReset = () => {
// 		building.init()
// 	}
// }

/**
 * 拆楼
 */
export const floor = ref('')

export const buildingOption = {
	layers: ['丰台站_-11_5', '丰台站_0_00', '丰台站_0m上'],
	spend: 50,
	displace: 0.5,
	totalDistance: 30,
	totalfloorDisplace: 680,
	floorSpend: 0.0001,
	floorDisplace: 20,
	direction: -155,
}
export let building: any = useBuilding(buildingOption as any)
export let isOpenBuilding = ref(false)
export const demolition = async () => {
	/**
	 * 抽拉方式
	 */
	// initSketch()
	// await building.init()
	// await fdapi.infoTree.hide(airStore.GetTreeIdByName(['丰台站整体', '0m上']))
	// await building.open()
	/**
	 * 显示隐藏方式
	 */
	fdapi.camera.set([12946254.542031, 4843636.294375, 447.990313, -33.205921, -117.927597, 0.000002], 1)
	fdapi.infoTree.show(airStore.GetTreeIdByName(['丰台分层']))
	fdapi.infoTree.hide(airStore.GetTreeIdByName(['丰台站整体']))
	openBuilding()
	initSketch()
	isOpenBuilding.value = true
}

export const exitDemolition = async (isCamera = true) => {
	/**
	 * 抽拉方式
	 */
	// building.exit()
	await fdapi.camera.unlock()
	initSketch(false)
	await closeBuilding()

	await fdapi.infoTree.show(airStore.GetTreeIdByName(['丰台站整体']))
	await fdapi.infoTree.hide(airStore.GetTreeIdByName(['丰台分层']))
	await fdapi.infoTree.show(airStore.GetTreeIdByName(['模型小品']))
	isOpenBuilding.value = false
	isCamera && fdapi.camera.set([12946254.542031, 4843636.294375, 447.990313, -33.205921, -117.927597, 0.000002], 1)
}
export const toggleFloor = async (item: any) => {
	floor.value = item.title
	fdapi.marker.clear()
	let fn: any = {
		多运输衔接层: 1,
		铁路安检层: 2,
	}
	await fdapi.infoTree.hide(airStore.GetTreeIdByName(['模型小品']))

	/**
	 * 抽拉方式
	 */
	// await building.toggleFloor(fn[item.title])
	// if (!building.isPullFloor.value) return
	//限制相机交互范围
	let bbox1 = [12946216.96, 4843903.04, 115, 12945716.48, 4844405.76, 700]
	let bbox2 = [12945694.72, 4844384.64, 75, 12946259.200000001, 4843990.72, 500]
	await fdapi.camera.lockByBBox(fn[item.title] == 1 ? bbox2 : bbox1)
	if (fn[item.title] == 1) {
		__g.tileLayer.show(airStore.GetTreeIdByName(['负11点5小品']))
		await fdapi.infoTree.show(airStore.GetTreeIdByName(['丰台站_-11_5']))
		await fdapi.infoTree.hide(airStore.GetTreeIdByName(['丰台站_0_00', '丰台站_0m上', '温湿度传感器']))
		await fdapi.camera.set([12946131.422656, 4843872.170117, 405.146914, -52.476563, -116.734932, 0.000003], 1)
	} else {
		__g.tileLayer.show(airStore.GetTreeIdByName('0层小品'))
		await fdapi.infoTree.show(airStore.GetTreeIdByName(['丰台站_0_00', '温湿度传感器']))
		await fdapi.infoTree.hide(airStore.GetTreeIdByName(['丰台站_-11_5', '丰台站_0m上']))
		await fdapi.camera.set([12946164.531562, 4843860.24957, 466.808867, -48.519516, -116.370804, 0.000008], 1)
	}
}

export const initSketch = async (flag = true) => {
	if (!isOpenBuilding.value && !flag) {
		return
	}
	let layersIds = airStore.GetTreeIdByName(['负11点5小品', '0层小品'])
	__g.tileLayer.hide(layersIds)
	const { data: infos } = await __g.tileLayer.get(layersIds)
	console.log('infos', infos)
	const yawRad = (buildingOption.direction * Math.PI) / 180
	infos.forEach((item: { id: string }, index: number) => {
		let x = infos[index].location[0]
		let y = infos[index].location[1]
		// let x = infos[index].location[0] + buildingOption.totalfloorDisplace * Math.cos(yawRad)
		// let y = infos[index].location[1] + buildingOption.totalfloorDisplace * Math.sin(yawRad)
		let z = infos[index].location[2] + buildingOption.totalDistance * (index + 1) * (flag ? 1 : -1)
		fdapi.tileLayer.setLocation(item.id, [x, y, z])
	})
}
let floors: any = []
export const openBuilding = async () => {
	const layersIds = airStore.GetTreeIdByName(['丰台站_-11_5', '丰台站_0_00', '丰台站_0m上'])
	const getTileLayer: any = await __g.tileLayer.get(layersIds)
	console.log('getTileLayer', getTileLayer)

	floors = getTileLayer.data
	const cloneFloors = JSON.parse(JSON.stringify(floors))
	let displace = 2
	let totalDistance = 30
	let total = 0
	const openTimer = setInterval(() => {
		__g.tileLayer.updateBegin()
		cloneFloors.forEach((tileLayer: any, index: number) => {
			tileLayer.location[2] = tileLayer.location[2] + displace * (index == 3 ? index : index + 1)
			__g.tileLayer.setLocation(tileLayer.id, tileLayer.location)
		})
		__g.tileLayer.updateEnd()
		total += displace
		if (total >= totalDistance) {
			clearInterval(openTimer)
		}
	}, 100)
}

export const closeBuilding = async () => {
	__g.tileLayer.updateBegin()
	floors.forEach((tileLayer: any, index: number) => {
		__g.tileLayer.setLocation(tileLayer.id, tileLayer.location)
	})
	await __g.tileLayer.updateEnd()
}
/**
 * 查询分析
 */

// 添加属性弹框
const addComponentInfoPupop = async (clickItem: any) => {
	// const result = await __g.tileLayer.getActorInfoFromDB({
	// 	tileLayerId: clickItem.Id,
	// 	objectIds: [clickItem.ObjectID],
	// })
	// console.log('data', result)

	// const data = result.data[clickItem.Id][clickItem.ObjectID].properties
	// console.log('data', data)
	// let resultData: any = {}
	// data.forEach((o: any) => {
	// 	for (const key in o) {
	// 		resultData[key] = o[key]
	// 	}
	// })
	// console.log('resultData', resultData)

	let info = {
		构件ID: '500E7B65485C569D848826854899FD10',
		族类别: '构件',
		族类别ID: '500E7B65485C',
		类型: 'tilelayer',
		类型ID: '500E7B65485C56',
	}
	await __g.marker.deleteByGroupId('componentinfo-marker')
	let m = {
		id: 'componentinfo',
		groupId: 'componentinfo-marker',
		coordinate: clickItem.MouseClickPoint, //坐标位置
		coordinateType: 0, //默认0是投影坐标系，也可以设置为经纬度空间坐标系值为1
		anchors: [0, 0], //锚点，设置Marker的整体偏移，取值规则和imageSize设置的宽高有关，图片的左上角会对准标注点的坐标位置。示例设置规则：x=-imageSize.width/2，y=imageSize.height
		imageSize: [50, 50], //图片的尺寸
		hoverImageSize: [50, 50], //鼠标悬停时显示的图片尺寸
		range: [1, 10000], //可视范围
		// imagePath: HostConfig.Path + '/samples/images/tag.png',//显示图片路径
		// hoverImagePath: HostConfig.Path + '/samples/images/hilightarea.png',// 鼠标悬停时显示的图片路径
		fixedSize: true, //图片固定尺寸，取值范围：false 自适应，近大远小，true 固定尺寸，默认值：false

		popupURL: window.origin + `/popup/componentInfo.html?info=${JSON.stringify(info)}`, //弹窗HTML链接
		popupBackgroundColor: [1, 1, 1, 1], //弹窗背景颜色
		popupSize: [550, 550], //弹窗大小
		popupOffset: [0, -30], //弹窗偏移

		showLine: false, //标注点下方是否显示垂直牵引线

		autoHidePopupWindow: false, //失去焦点后是否自动关闭弹出窗口
		autoHeight: false, // 自动判断下方是否有物体
		priority: 0, //避让优先级
		occlusionCull: false, //是否参与遮挡剔除
	}

	await __g.marker.add(m)
	await __g.marker.showPopupWindow('componentinfo')
}
//点选
export let isSearchInfo = ref(false)
export const searchInfo = async (e: any) => {
	if (isSearchInfo.value) {
		await fdapi.tileLayer.stopHighlightAllActors()
		fdapi.settings.highlightColor(Color.Blue)
		fdapi.tileLayer.highlightActor(e.Id, e.ObjectID)
		addComponentInfoPupop(e)
	}
}
export const clearSearchInfo = async () => {
	isSearchInfo.value = false
	await fdapi.tileLayer.stopHighlightAllActors()
	await __g.marker.deleteByGroupId('componentinfo-marker')
}
//量测-直线
export const measure = async () => {
	await __g.tools.setMeasurement(2, {
		pointSize: 20,
		textSize: 18,
		textColor: [1, 1, 1],
		pointColor: [1, 1, 1, 1],
		lineColor: [0, 232 / 255, 1],
		areaColor: [0, 0.2, 1, 0.1],
		showCoordinateText: false,
	})
	await __g.tools.startMeasurement()
}
export const clearMeasure = async () => {
	await __g.tools.stopMeasurement(null)
}
//可视域
export const viewfield = () => {
	let ops = {
		fov_h: 60, // 水平视角，取值范围：[1°~150°]
		fov_v: 30, // 垂直视角，取值范围：[1°~150°]
		height: 2, // 视点高度（距离场景交互所拾取点的高度）
		visibleColor: '#00ff00', // 可见区域的颜色
		invisibleColor: '#ff0000', // 不可见区域的颜色
		//interactiveLock: true, // 是否开启交互锁定
	}
	__g.tools.startViewshedAnalysis(ops)
}
export const clearViewfield = async () => {
	await __g.tools.stopViewshedAnalysis()
}
//等高面
export const contour = async () => {
	await __g.tools.startContourLineAnalysis({
		isShowContourPlane: true, //是否显示等高面，{boolean}，默认值：true
		contourPlaneOpacity: 1.0, //等高面颜色不透明度，仅当isShowContourPlane设置为true时生效，{number}，取值范围：[0~1]，默认值：1
		isShowContourLine: true, //是否显示等高线，{boolean}，默认值：true
		contourLineColor: [1, 1, 1, 1], //等高线颜色值，仅当isShowContourLine设置为true时生效，{Color}，默认值：[1,1,1,1]
		contourLineSpacing: 0.1, //等高线的间距，仅当isShowContourLine设置为true时生效，{number}，单位：米，默认值：20米
		contourLineRangeMax: 1000000, //等高线最大可视高度，{number}，单位：米，默认值：1000000米
		contourLineRangeMin: -1000000, //等高线最小可视高度，{number}，单位：米，默认值：-1000000米
	})
}
export const clearContour = async () => {
	await fdapi.tools.stopContourLineAnalysis()
}

//添加地铁站点

export const addMetroStation = async () => {
	await fdapi.infoTree.deleteByGroupId('metro-marker')
	let list = [
		{
			name: '丰台地铁站C1口',
			coordinate: [12946426.88, 4843898.5600000005, 70.9665771484375],
			lineColor: [12946195.0, 4844110.0, 88.7],
			color: [0, 0.25, 1, 1],
			groupId: 'metro-marker',
			animId: 'C1',
		},
		{
			name: '丰台地铁站C2口',
			coordinate: [12946408.96, 4844034.5600000005, 70.9666015625],
			lineColor: [12946195.0, 4844110.0, 88.7],
			color: [0, 0.25, 1, 1],
			groupId: 'metro-marker',
			animId: 'C2',
		},
		{
			name: '丰台地铁站D口',
			coordinate: [12946296.32, 4843948.48, 70.9666015625],
			lineColor: [12946195.0, 4844110.0, 88.7],
			color: [0, 0.25, 1, 1],
			groupId: 'metro-marker',
			animId: 'D',
		},
	]
	addAreaMarker3d(list)
	// setTimeout(() => {
	// 	fdapi.infoTree.show(airStore.GetTreeIdByName(['地铁站标签']))
	// }, 2000)
}

export const playStationAnimation = async (e: any) => {
	// console.log('e', e)
	// if (e.Id) {
	// 	console.log('airStore.animationList', airStore.animationList)
	// 	let i = airStore.animationList.findIndex((_: any) => (_.name = e.Id))
	// 	fdapi.camera.playAnimation(i)
	// }
}

/**
 * 导流牌标签
 */
export const addDlpMarker = () => {
	let coordinate = [12946193.92, 4844056.64, 80.48126953125]
	fdapi.marker.delete('DlpMarker')
	let o1 = {
		id: 'DlpMarker',
		groupId: 'DlpMarker',
		coordinate: coordinate, //坐标位置
		coordinateType: 0, //默认0是投影坐标系，也可以设置为经纬度空间坐标系值为1
		anchors: [-25, 50], //锚点，设置Marker的整体偏移，取值规则和imageSize设置的宽高有关，图片的左上角会对准标注点的坐标位置。示例设置规则：x=-imageSize.width/2，y=imageSize.height
		imageSize: [50, 50], //图片的尺寸
		hoverImageSize: [50, 50], //鼠标悬停时显示的图片尺寸
		range: [0, 100000], //可视范围
		viewHeightRange: [0, 10000], // 可见高度范围
		rangeRatio: 0.01, //可见高度范围的调整系数
		// imagePath: HostConfig.Path + '/samples/images/tag.png', //显示图片路径
		// hoverImagePath: HostConfig.Path + '/samples/images/hilightarea.png', // 鼠标悬停时显示的图片路径
		fixedSize: true, //图片固定尺寸，取值范围：false 自适应，近大远小，true 固定尺寸，默认值：false

		text: '', //显示的文字
		useTextAnimation: false, //关闭文字展开动画效果 打开会影响效率
		textRange: [1, 1000], //文本可视范围[近裁距离, 远裁距离]
		textOffset: [0, 0], // 文本偏移
		textBackgroundColor: Color.SpringGreen, //文本背景颜色
		fontSize: 24, //字体大小
		fontOutlineSize: 1, //字体轮廓线大小
		fontColor: Color.White, //字体颜色
		fontOutlineColor: Color.Black, //字体轮廓线颜色

		popupURL: `${window.origin}/popup/equipmentInfo2.html`, //弹窗HTML链接
		popupBackgroundColor: [1.0, 1.0, 1.0, 1], //弹窗背景颜色
		popupSize: [1000, 600], //弹窗大小
		popupOffset: [0, 0], //弹窗偏移

		showLine: false, //标注点下方是否显示垂直牵引线
		lineSize: [2, 100], //垂直牵引线宽度和高度[width, height]
		lineColor: Color.SpringGreen, //垂直牵引线颜色
		lineOffset: [0, 0], //垂直牵引线偏移

		autoHidePopupWindow: true, //失去焦点后是否自动关闭弹出窗口
		autoHeight: false, // 自动判断下方是否有物体
		displayMode: 4, //智能显示模式  开发过程中请根据业务需求判断使用四种显示模式
		clusterByImage: true, // 聚合时是否根据图片路径分类，即当多个marker的imagePath路径参数相同时按路径对marker分类聚合
		priority: 0, //避让优先级
		occlusionCull: false, //是否参与遮挡剔除
	}
	fdapi.marker.add(o1)
	// fdapi.marker.focus(o1.id)
	fdapi.camera.set([12946211.744219, 4844073.728984, 80.993994, 0, 149.999954, 0], 1)
	fdapi.marker.showPopupWindow(o1.id)
}

/**
 *应急演练
 */

//添加火焰
export const addFire = async (coords: number[][]) => {
	const objs = coords.map((location, i) => {
		return {
			id: 'fire' + i, //自定义对象唯一id
			pakFilePath: '@path:DTS_Library.pak', //资源库pak文件路径,推荐使用cloud内置的文件资源管理器加载pak并使用@path方式传入参数
			assetPath: '/Game/Common/Asset_Bank/Mesh/Car/BP_Car_JiuHuChe', //资源目录，自定义对象在pak文件资源包里的相对路径
			location: location, //位置坐标
			coordinateType: 0, // 坐标系类型
			rotation: [0, 0, 0], // 世界坐标系旋转
			range: [0, 10000000], //可见范围
			groupId: 'fire', //分组id
			localRotation: [0, 0, 0], //模型自身旋转
			scale: [1, 1, 1], //模型缩放
			isEffectRotation: true, //是否开启旋转效果
			smoothMotion: 1, //1: 平滑移动，0: 跳跃移动
			supportAttach: false, //不支持贴画贴合
			visible: true, //模型加载后默认是否显示
		}
	})
	await fdapi.customObject.add(objs)
}

//添加逃生路线
export const addEscapeLine = async (lines: any) => {
	const objs = lines.map((item: any, i: number) => {
		return {
			id: 'escapeLines' + i, //折线唯一标识id
			groupId: 'escapeLines', //分组id
			coordinates: item.coordinates, //构成折线的坐标点数组
			coordinateType: 0, //坐标系类型，取值范围：0为Projection类型，1为WGS84类型，2为火星坐标系(GCJ02)，3为百度坐标系(BD09)，默认值：0
			range: [1, 100000000], //可视范围：[近裁距离, 远裁距离]，取值范围: [任意负值, 任意正值]
			color: Color.Red, //折线颜色
			thickness: 100, //折线宽度
			intensity: 0.3, //亮度
			flowRate: 0.5, //流速
			shape: 0, //折线类型 0：直线， 1：曲线
			depthTest: false, //是否做深度检测 开启后会被地形高度遮挡
			style: 1, //折线样式 参考样式枚举：PolylineStyle
			tiling: 0, //材质贴图平铺比例
		}
	})
	await fdapi.polyline.add(objs)
}

//添加动态人物
export const addEscapePerson = async (lines: any) => {
	const objs = lines.map((item: any, i: number) => {
		return {
			id: 'EscapePerson' + i, //自定义对象唯一id
			pakFilePath: '@path:DTS_Library.pak', //资源库pak文件路径,推荐使用cloud内置的文件资源管理器加载pak并使用@path方式传入参数
			assetPath: '/Game/Common/Asset_Bank/Mesh/Car/BP_Car_JiuHuChe', //资源目录，自定义对象在pak文件资源包里的相对路径
			location: item.coordinates[0], //位置坐标
			coordinateType: 0, // 坐标系类型
			rotation: [0, 0, 0], // 世界坐标系旋转
			range: [0, 10000000], //可见范围
			groupId: 'EscapePerson', //分组id
			localRotation: [0, 0, 0], //模型自身旋转
			scale: [1, 1, 1], //模型缩放
			isEffectRotation: true, //是否开启旋转效果
			smoothMotion: 1, //1: 平滑移动，0: 跳跃移动
			supportAttach: false, //不支持贴画贴合
			visible: true, //模型加载后默认是否显示
		}
	})
	await fdapi.customObject.add(objs)
	// 切换跑步
	const temporary = objs.map((item: any) => {
		return {
			id: item.id,
			functionName: '动画类型',
			parameters: [{ paramType: 5, paramValue: '跑步' }],
		}
	})
	await __g.customObject.callBatchBPFunction(temporary)
}

//人物按逃生路线奔跑
export const runPerson = (id: string, positionArr: number[][]) => {
	//构造移动路径点数组
	let pathPointArr = positionArr.map((coordinate, i) => {
		return { time: i * 0.5, coordinate }
	})
	fdapi.customObject.startMove(id, 0, pathPointArr)
}

//清除应急演练
export const clearEmergencyDrill = () => {
	fdapi.infoTree.deleteByGroupId('fire')
	fdapi.infoTree.deleteByGroupId('escapeLines')
	fdapi.infoTree.deleteByGroupId('EscapePerson')
}
